将给定的链表中每两个相邻的节点交换一次,返回链表的头指针
例如,
给出1->2->3->4,你应该返回链表2->1->4->3。
你给出的算法只能使用常量级的空间。你不能修改列表中的值,只能修改节点本身。
class Solution: def swapPairs(self , head ): if not head&nbs***bsp;not head.next: return head # 定义虚结点头 dummy = move = ListNode(0) # 成对指针转移 pre, cur = head, head.next # 遍历链表 while cur: # 拆分指向 pre.next = cur.next cur.next = pre # 确定指向 move.next = cur move = pre # 下一对 pre = pre.next # 没有下一对了 if not pre: break cur = pre.next # 返回交换完成的链表 return dummy.next